# -*- coding: utf-8 -*-

import os
import cv2
import data5.config as config
import data5.utils as utils


def nothing(x):
    pass


def show(image):
    cv2.namedWindow('image', 0)

    cv2.createTrackbar('blur', 'image', 0, 50, nothing)
    cv2.createTrackbar('threshold', 'image', 202, 255, nothing)
    image_copy = image
    while True:
        _, contours, hierarchy = cv2.findContours(image_copy, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
        for i in range(len(hierarchy[0])):
            if hierarchy[0][i][3] == 0:
                x, y, w, h = cv2.boundingRect(contours[i])
                if w > 10 and h > 10:
                    cv2.rectangle(image_copy, (x, y), (x + w, y + h), (0, 0, 255), 1)

        cv2.imshow('image', image_copy)

        if cv2.waitKey(10) & 0xFF == ord('q'):
            break
        blur = cv2.getTrackbarPos('blur', 'image')
        if blur % 2 == 0:
            blur = blur + 1
        threshold = cv2.getTrackbarPos('threshold', 'image')
        image_copy = cv2.medianBlur(image, blur)
        _, image_copy = cv2.threshold(image_copy, threshold, 255, cv2.THRESH_BINARY)

    cv2.destroyAllWindows()


if __name__ == '__main__':

    img = utils.load_image_by_filename(os.path.join(config.yzm_path, '0001.jpg'))
    show(img)
